<template>
  <el-container style="height: 100vh; overflow: hidden">
    <el-header
      height="50px"
      style="border-bottom: 1px solid #eee; display: flex; align-items: center; justify-content: flex-end; gap: 10px; padding-right: 20px;"
    >
      <el-button type="primary" @click="saveTemplate">保存模板</el-button>
      <el-button type="success" @click="publishTemplate">发布模板</el-button>
      <el-button type="info" @click="previewTemplate">预览模板</el-button>
    </el-header>

    <el-container style="height: calc(100vh - 50px)">
      <el-aside
        width="220px"
        style="border-right: 1px solid #eee; padding: 10px; overflow-y: auto"
      >
        <ModuleLibrary @add-module="addModule" />
      </el-aside>

      <el-main
        style="padding: 10px; overflow-y: auto; background: #fafafa; display: flex; justify-content: center;"
      >
        <div
          style="width: 375px; background: white; border-radius: 8px; box-shadow: 0 0 12px rgba(0,0,0,0.1); padding: 15px; box-sizing: border-box;"
        >
          <draggable v-model="modules" group="modules" @end="onDragEnd">
            <transition-group name="fade" tag="div">
              <BaseModuleWrapper
                v-for="mod in modules"
                :key="mod.id"
                :component="getComponentByType(mod.type)"
                :module="mod"
                :isSelected="selectedModule && mod.id === selectedModule.id"
                @update-module="updateModule"
                @select-module="selectModule(mod)"
                @delete-module="removeModule(mod.id)"
                @sync-search-bg="syncSearchBgColor"
                @sync-banner-bg="syncBannerBgColor"
              />
            </transition-group>
          </draggable>
        </div>
      </el-main>

      <el-aside
        width="300px"
        style="border-left: 1px solid #eee; padding: 10px; overflow-y: auto"
      >
        <PropertyPanel
          v-if="selectedModule"
          :module="selectedModule"
          @update-module="updateModule"
          @sync-search-bg="syncSearchBgColor"
          @sync-banner-bg="syncBannerBgColor"
        />
      </el-aside>
    </el-container>
  </el-container>
</template>


<script>
import draggable from "vuedraggable";
import ModuleLibrary from "./ModuleLibrary.vue";
import PropertyPanel from "./PropertyPanel.vue";
import BaseModuleWrapper from "./BaseModuleWrapper.vue";

export default {
  components: {
    draggable,
    ModuleLibrary,
    PropertyPanel,
    BaseModuleWrapper,
  },
  data() {
    return {
      modules: JSON.parse(localStorage.getItem("template_modules") || "[]"),
      selectedModule: null,
    };
  },
  methods: {
    addModule(type) {
      const defaultProps = {
        SubjectSelector: {
          subjects: ["语文", "数学", "英语"], // 默认几个文本标题
          bgColor: "#f5f5f5", // 默认背景色
          textColor: "#333", // 默认文字颜色
          fontSize: "16px", // 字体大小
          padding: "10px", // 内边距
        },
        Search: { placeholder: "请输入关键词" },
        Banner: {
          images: ["https://picsum.photos/600/200?random=1"],
          autoplay: true,
        },
        Notice: { text: "这是公告内容" },
        FunctionEntry: { entries: [{ icon: "el-icon-user", title: "功能1" }] },
        QuickEntry: { entries: [{ icon: "el-icon-setting", title: "快捷1" }] },
        BrandRecommend: { brands: [{ name: "品牌A" }] },
        RichContent: { content: "" },
        ImageLink: { image: "https://picsum.photos/300/150", link: "#" },
        Video: { src: "https://www.w3schools.com/html/mov_bbb.mp4" },
        Courseware: { title: "课件标题", url: "#" },
        Product: {
          products: [
            {
              name: "商品 A",
              price: 199,
              image: "https://via.placeholder.com/150",
            },
            {
              name: "商品 B",
              price: 299,
              image: "https://via.placeholder.com/150",
            },
          ],
        },
        Column: { title: "专栏标题", content: "专栏内容" },
        ExternalProduct: { name: "外链商品", url: "#" },
        Vote: { question: "你喜欢哪个模块？", options: ["轮播", "公告"] },
        ContentList: { items: ["内容1", "内容2"] },
      };
      const newModule = {
        id: Date.now(),
        type,
        props: defaultProps[type] || {},
      };
      this.modules.push(newModule);
      this.selectedModule = newModule;
    },
    removeModule(id) {
      this.modules = this.modules.filter((m) => m.id !== id);
      if (this.selectedModule?.id === id) this.selectedModule = null;
    },
    selectModule(module) {
      this.selectedModule = module;
    },
    updateModule(updatedModule) {
      if (!updatedModule || !updatedModule.id) return;
      const idx = this.modules.findIndex((m) => m.id === updatedModule.id);
      if (idx !== -1) this.modules.splice(idx, 1, updatedModule);
    },
    onDragEnd() {
      localStorage.setItem("template_modules", JSON.stringify(this.modules));
    },
    saveTemplate() {
      localStorage.setItem("template_modules", JSON.stringify(this.modules));
      this.$message.success("模板已保存");
    },
    publishTemplate() {
      // 这里你可以调用后端接口提交数据
      console.log("发布模板数据:", this.modules);
      this.$message.success("模板已发布");
    },
    previewTemplate() {
      localStorage.setItem(
        "preview_template_modules",
        JSON.stringify(this.modules)
      );
      window.open("/preview.html", "_blank");
    },
    getComponentByType(type) {
      const map = {
        SubjectSelector: require("./modules/SubjectSelectorModule.vue").default,
        Search: require("./modules/SearchBarModule.vue").default,
        Banner: require("./modules/BannerModule.vue").default,
        Notice: require("./modules/NoticeModule.vue").default,
        FunctionEntry: require("./modules/FunctionEntryModule.vue").default,
        QuickEntry: require("./modules/QuickEntryModule.vue").default,
        BrandRecommend: require("./modules/BrandRecommendModule.vue").default,
        RichContent: require("./modules/RichContentModule.vue").default,
        ImageLink: require("./modules/ImageLinkModule.vue").default,
        Video: require("./modules/VideoModule.vue").default,
        Courseware: require("./modules/CoursewareModule.vue").default,
        Product: require("./modules/ProductModule.vue").default,
        Column: require("./modules/ColumnModule.vue").default,
        ExternalProduct: require("./modules/ExternalProductModule.vue").default,
        Vote: require("./modules/VoteModule.vue").default,
        ContentList: require("./modules/ContentListModule.vue").default,
      };
      return map[type] || "div";
    },
    syncSearchBgColor(bgColor) {
      this.modules.forEach((mod, index) => {
        if (mod.type === "Search") {
          const newProps = { ...mod.props, bgColor };
          this.modules.splice(index, 1, { ...mod, props: newProps });
        }
      });
    },
    syncBannerBgColor(bgColor) {
      this.modules.forEach((mod, index) => {
        if (mod.type === "Banner") {
          const newProps = { ...mod.props, bgColor };
          this.modules.splice(index, 1, { ...mod, props: newProps });
        }
      });
    },
  },
};
</script>
